<?php
namespace App\Goods\Http\Controllers;


use App\ApiBaseController;
use App\Exceptions\GoodsException;
use App\Goods\Models\CommonName;
use App\Goods\Services\CommonNameService;
use App\Goods\Services\GoodsAttrService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CommonNameController extends ApiBaseController
{
    /**
     * 通用名列表
     */
    public function index()
    {

    }

    /**
     * 通用名添加表单验证
     * @param $data
     * @param $type
     * @return array
     * @throws GoodsException
     */
    private function validate($data, $type)
    {
        switch($type){
            case 'create':
                if(empty($data['name'])){
                    throw new GoodsException('请输入通用名名称！');
                }
                if(empty($data['attr'])){
                    throw new GoodsException('请填写通用名属性！');
                }
                break;
            case 'spu':
                if(empty($data['name'])){
                    throw new GoodsException('请输入通用名名称！');
                }
                if(empty($data['dosage'])){
                    throw new GoodsException('请选择剂型！');
                }
                break;
            default:
                return [];
        }
        return $data;
    }

    /**
     * 通用名添加
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request)
    {
        $param = $request->input();

        try {
            // 表单验证
            $data = $this->validate($param, 'create');

            $service = new CommonNameService();
            $res = $service->saveCommonName($data);
            if(!$res){
                throw new GoodsException('添加失败！');
            }
            return $this->success('添加成功！', $res);
        }catch(GoodsException $exception){
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 生成SPU
     * @param Request $request
     * @return string
     */
    public function spu(Request $request)
    {
        $param = $request->input();
        try{
            $data = $this->validate($param, 'spu');

            $service = new CommonNameService();
            $spu = $service->setSpu($data);
            return $this->success('success', [
                'spu' => $spu
            ]);
        }catch (GoodsException $exception){
            return $this->error('添加失败！');
        }
    }

    /**
     * 查询通用名详情数据
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $service = new CommonNameService();
            $result = $service->getInfo($id);
            return $this->success('success', $result);
        }catch (GoodsException $exception){
            return $this->error($exception->getMessage());
        }
    }





}
